<template>
  <div class="message" :class="{ 'message-self': isSelf }">
    <div class="avatar">
      <img 
        v-if="message.from_head_img && isValidUrl(message.from_head_img)" 
        :src="message.from_head_img" 
        :alt="message.from_name"
        @error="handleImageError"
      />
      <span v-else>{{ getInitials(message.from_name) }}</span>
    </div>
    <div class="message-wrapper">
      <div class="message-sender">{{ message.from_name }}</div>
      <div class="message-content">
        {{ message.content }}
      </div>
      <div class="message-time">
        {{ formatTime(message.timestamp) }}
      </div>
    </div>
  </div>
</template>
  
<script setup>
import { computed } from 'vue'
import { userService } from '@/services/userService'

const props = defineProps({
  message: {
    type: Object,
    required: true
  }
})

const currentUser = computed(() => userService.getUser())
const isSelf = computed(() => props.message.from === currentUser.value.uid)

const formatTime = (date) => {
  return new Date(date).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getInitials = (name) => {
  if (!name) return ''
  return name.charAt(0).toUpperCase()
}

const isValidUrl = (url) => {
  try {
    new URL(url)
    return true
  } catch {
    return false
  }
}
</script>
  
  <style scoped>
  .avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 14px;
    overflow: hidden;
    position: relative;
  }

  .avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    position: absolute;
    top: 0;
    left: 0;
  }

  .avatar span {
    z-index: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
  }

  .message-self .avatar {
    background-color: #07c160;
  }
  .message-sender {
    font-size: 12px;
    color: #666;
    margin-bottom: 4px;
  }
  .message {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }
  
  .message-self {
    flex-direction: row-reverse;
  }
  
  .message-wrapper {
    max-width: 70%;
  }
  
  .message-content {
    padding: 10px;
    border-radius: 10px;
    background-color: white;
    word-break: break-all;
  }
  
  .message-self .message-content {
    background-color: #95ec69;
  }
  
  .message-time {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
    text-align: center;
  }
  </style>